#include "nodeChannel.h"
#include <time.h>
#include "utils/helper.h"

using namespace v8;
namespace privacy_service
{
NodeChannel::NodeChannel()
{	
	
}
void NodeChannel::buildConnect()
{
	async_.data = this;
	uv_async_init(uv_default_loop(), &async_, asyncCb);
}

void NodeChannel::removeConnect()
{
	uv_close((uv_handle_t*)&async_, closeCb);
}
bool NodeChannel::callMainThread(std::string data, PersistentPtr cb)
{
	ResponseData *resp = new ResponseData;
	resp->info = data;
	resp->cb = cb;

	responseDatas_.push(resp);
	uv_async_send(&async_);
	return true;
}

void NodeChannel::asyncCb(uv_async_t* handle)
{
	NodeChannel* channel = (NodeChannel*)handle->data;
	Queue &responseDatas = channel->responseDatas_;

	void *data = nullptr;
	while ((data = responseDatas.tryPop()) != nullptr)
	{
		ResponseData *resp = (ResponseData*)data;
		MAKE_DATA();
#ifdef ELECTRON_8

		v8::Local<v8::String> result = v8::String::NewFromUtf8(isolate, resp->info.c_str(), v8::NewStringType::kNormal).ToLocalChecked();
#else
		v8::Local<v8::String> result = v8::String::NewFromUtf8(isolate, resp->info.c_str());
#endif
		v8::Local<Context> context = v8::Context::New(isolate);
		v8::Context::Scope context_scope(context);

		auto maybeResultValue = JSON::Parse(context, result);
		v8::Local<v8::Value> resultValue;
		maybeResultValue.ToLocal(&resultValue);
		if (!resultValue->IsUndefined() && resultValue->IsObject()) jsObject = v8::Local<v8::Object>::Cast(resultValue);
		Helper::callJsCallback(isolate, resp->cb, jsObject);
		delete resp;
	}
}

void NodeChannel::closeCb(uv_handle_t* handle)
{
	
}
} /*namespace privacy_service*/
